﻿using System;
using System.Net;
using System.Windows;
using SL8.SL.Extensions;
using System.Windows.Input;
using System.Windows.Interactivity;
using SL8.SL.Controls;

namespace SL8.SL.Actions
{
    public class TriggerValidateAction : TargetedTriggerAction<DependencyObject>
    {
        protected override void Invoke(object parameter)
        {
            if (this.Target == null || this.Target == this.AssociatedObject)
            {
                ValidatePanel validatePanel = this.AssociatedObject.GetParent<ValidatePanel>();

                if (validatePanel != null)
                {
                    bool isValid = validatePanel.ValidateChildDataFields();
                    ICommand command = ValidateService.GetValidateCommand(validatePanel);

                    if (command == null)
                    {
                        command = ValidateService.GetValidateCommand(this.AssociatedObject);

                        if (command.CanExecute(isValid))
                        {
                            command.Execute(isValid);
                        }
                    }
                }
            }
            else
            {
                bool isValid = this.Target.ValidateChildDataFields();

                ICommand command = ValidateService.GetValidateCommand(this.Target);
                if (command != null)
                {
                    if (command.CanExecute(isValid))
                    {
                        command.Execute(isValid);
                    }
                }
            }
        }
    }
}
